from tkinter import Frame
import tkinter as tk
import cv2.cv2 as cv
import numpy as np
import pygame
from PIL import Image, ImageTk
import sys
import pygame
import time

detector = cv.CascadeClassifier('haarcascade_frontalface_alt2.xml')
nose_cascade = cv.CascadeClassifier('haarcascade_mcs_nose.xml')
mask_detector = cv.CascadeClassifier('mask.xml')
file_slogan_short = r'slogan_short.mp3'
pygame.mixer.init(frequency=16000, size=-16, channels=2, buffer=4096)
recognizer = cv.face.LBPHFaceRecognizer_create()
recognizer.read('face_trainer/trainer1.yml')

class GUI:
    def __init__(self):
        self.camera = None  # 摄像头
        self.root = tk.Tk()
        self.root.title('Mask detection')
        self.root.geometry('550x400+450+250')
        self.createFirstPage()
        self.root.mainloop()


    def createFirstPage(self):
        self.page1 = Frame(self.root)
        self.page1.pack()
        self.text = tk.Label(self.page1, text="口罩检测系统", bg="yellow", fg="red", font=('Times', 20, 'bold italic'))
        self.text.pack()
        image = Image.open("2.gif")
        photo = ImageTk.PhotoImage(image=image)
        self.data1 = tk.Label(self.page1, width=780, image=photo)
        self.data1.image = photo
        self.data1.pack(padx=5, pady=5)
        self.b1 = tk.Button(self.page1, text='实时监测', command=self.createSecondPage)
        self.b1.pack(side='left', padx=25, pady=10)
        self.b2 = tk.Button(self.page1, text='关闭', command=self.quitMain)
        self.b2.pack(side='left', padx=25, pady=10)


    def createSecondPage(self):
        self.camera = cv.VideoCapture(0, cv.CAP_DSHOW)
        self.page1.pack_forget()
        self.page2 = Frame(self.root)
        self.page2.pack()
        tk.Label(self.page2, text='欢迎使用口罩检测系统', font=('粗体', 20)).pack()
        self.data2 = tk.Label(self.page2)
        self.data2.pack(padx=10, pady=10)
        #self.b3 = tk.Button(self.page2, text='关闭', command=self.backFirst)
        #self.b3.pack(side='left', padx=25, pady=10)
        self.video_loop(self.data2)


    def video_loop(self, panela):
        def slogan_short():
            timeplay = 1.5
            global playflag_short
            playflag_short = 1
            while playflag_short:
                track = pygame.mixer.music.load(file_slogan_short)
                print("------------请您戴好口罩")
                pygame.mixer.music.play()
                time.sleep(timeplay)
                playflag_short = 0
            time.sleep(0)

        success, img = self.camera.read()
        if success:
            faces = detector.detectMultiScale(img, 1.1, 3)
            result1 = []
            result2 = []
            a = 'no_mask'
            b = 'have_mask'
            for (x, y, w, h) in faces:
                fac_gray = img[y: (y + h), x: (x + w)]
                result = []
                mask_face = mask_detector.detectMultiScale(fac_gray, 1.3, 2)
                noses = nose_cascade.detectMultiScale(fac_gray, 1.2, 10)
                # 眼睛坐标的换算，将相对位置换成绝对位置
                for (mx, my, mw, mh) in mask_face:
                    result1.append((x + mx, y + my, mw, mh))
                for (nx, ny, nw, nh) in noses:
                    result2.append((x + nx, y + ny, nw, nh))

            # 搜索人的鼻子
            for (nx, ny, nw, nh) in result2:
                cv.rectangle(img, (nx, ny), (nx + nw, ny + nh), (10, 10, 255), 2)
                cv.putText(img, a, (nx, ny), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                slogan_short()
                #self.face_recognition()

            # mask
            for (mx, my, mw, mh) in result1:
                cv.rectangle(img, (mx, my), (mx + mw, my + mh), (0, 255, 0), 2)
                cv.putText(img, b, (mx, my), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

            cv2image = cv.cvtColor(img, cv.COLOR_BGR2RGBA)  # 转换颜色从BGR到RGBA

            current_image = Image.fromarray(cv2image)  # 将图像转换成Image对象
            imgtk = ImageTk.PhotoImage(image=current_image)
            panela.imgtk = imgtk
            panela.config(image=imgtk)
            self.root.after(1, lambda: self.video_loop(panela))



    def face_recognition(self):
        idnum = 0
        names = ['Bob', 'Ella', 'Other', 'None']

    '''    
    def backFirst(self):
        self.page2.pack_forget()
        self.page1.pack()
        # 释放摄像头资源
        self.camera.release()
        cv.destroyAllWindows()
    '''
    def quitMain(self):
        sys.exit(0)

if __name__ == '__main__':
    demo = GUI()




